//
//  MFCycleImage.m
//  CollectionView轮播图-封装
//
//  Created by mafeng on 16/8/4.
//  Copyright © 2016年 mafeng. All rights reserved.
//

#import "MFCycleImage.h"
#define kRandomColor [UIColor colorWithRed:arc4random() % 256 / 255.0f green:arc4random() % 256 / 255.0f blue:arc4random() % 256 / 255.0f alpha:1]
#define kCollectionViewCell @"reuse"
#define kWidth self.bounds.size.width
#define kHeight self.bounds.size.height
@interface MFCycleImage ()<UICollectionViewDelegate, UICollectionViewDataSource>
@property (nonatomic, strong) UIPageControl *page;
@property (nonatomic, strong) NSMutableArray *imageArray;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UICollectionViewFlowLayout *layout;
@property (nonatomic, strong) NSTimer *timer;
@end

@implementation MFCycleImage

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

   // 用sb的时候走这个方法, 不走initWithFrame
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        self.backgroundColor = [UIColor redColor];
        [self setUp];
        // 在这self.view.frame.width是0, 所以不能进行控件的创建
    }
    return self;
}

- (void)setUp {
    [self createCollectionView];
    [self createPageController];
    [self addTimer];
}
  // 添加 timer
- (void)addTimer {
    // <<-以timer打头->>仅仅是创建一个定时器, 并未有加在loop中
    self.timer = [NSTimer timerWithTimeInterval:2 target:self selector:@selector(add) userInfo:nil repeats:YES];
    
    [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSDefaultRunLoopMode];
    // NSRunLoopCommonModes 和 NSDefaultRunLoopMode
    // 后者代表默认状态, scheduleTimerWithTimerInterval添加为默认状态
    // 前者为多种状态, 包含默认 和 滚动
    
    
    // 创建一个timer并添加到loop中
    //NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(add) userInfo:nil repeats:YES];
    
   
}
  // 移除 timer
- (void)removeTimer {
    // 取消timer时, 调用 invalidate
    [_timer invalidate];
    // timer 一定要置空
    _timer = nil;
}
  // timer 定时执行的方法
- (void)add {
    [_collectionView setContentOffset:CGPointMake(_collectionView.contentOffset.x + kWidth, 0) animated:YES];
    
    if (_collectionView.contentOffset.x == (_array.count - 1) * kWidth) {
        [_collectionView setContentOffset:CGPointMake(kWidth, 0)];
        // 还要设置一下page
        _page.currentPage = 1;
    } else {
        _page.currentPage++;
    }
    
}

- (void)createPageController {
    self.page = [[UIPageControl alloc] initWithFrame:CGRectZero];
    [_page addTarget:self action:@selector(pageAction:) forControlEvents:UIControlEventValueChanged];
    [self addSubview:_page];
}

- (void)createCollectionView {
    self.layout = [[UICollectionViewFlowLayout alloc] init];
    _layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    _layout.minimumLineSpacing = 0;
    _layout.minimumInteritemSpacing = 0;
    // 在这里先不写frame的大小(包括设置属性时数值与bounds或frame有关系), 因为这里的self的frame为0.
    // 要在layout里面写!!!!!!
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:_layout];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
     [self addSubview:_collectionView];
    _collectionView.pagingEnabled = YES;
    // 注册
    [_collectionView registerClass:[MFCycleImageCell class] forCellWithReuseIdentifier:kCollectionViewCell];

}

- (void)layoutSubviews {
    [super layoutSubviews];
    _collectionView.frame = self.bounds;
    _layout.itemSize = self.bounds.size;
    _page.frame = CGRectMake(0, 0, kWidth / 3, 20);
    _page.center = CGPointMake(kWidth / 2, kHeight - 20 / 2);
    NSLog(@"%@", NSStringFromCGRect(self.bounds));
    NSLog(@"%@", NSStringFromCGSize(self.bounds.size));
    NSLog(@"%@", NSStringFromCGSize(_layout.itemSize));
    _page.numberOfPages = _array.count - 2;
    _collectionView.contentOffset = CGPointMake(kWidth, 0);
}

  // 重写是初始化方法是父类的
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
          }
    return self;
}
  // page 的监听事件
- (void)pageAction:(UIPageControl *)page {
    _collectionView.contentOffset = CGPointMake(kWidth * page.currentPage, 0);
}
  // 当滑动减速结束时
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (scrollView == _collectionView) {
        _page.currentPage = _collectionView.contentOffset.x / kWidth -1;
    }
    if (scrollView.contentOffset.x == 0) {
        
        [_collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:_array.count - 2 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
        // 还要设置一下page
        _page.currentPage = _array.count - 3;
        
    } else if (scrollView.contentOffset.x == kWidth * (_array.count - 1)) {
        [_collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem: 1 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
        // 还要设置一下page
        _page.currentPage = 0;
    }
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _array.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    MFCycleImageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kCollectionViewCell forIndexPath:indexPath];
    cell.backgroundColor = kRandomColor;
    
    [self.delegate handleDataWithObject:_array[indexPath.row] cell:cell];
    //cell.label.text = @"mafeg";
    //cell.cycleImage.image = [UIImage imageNamed:_array[indexPath.row]];
    return cell;
}

- (void)setArray:(NSArray *)array {
    _array = array;
    [_collectionView reloadData];
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"$$$$$%@", indexPath);
    [self.delegate didSelect];
    
}

@end

@implementation MFCycleImageCell

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        _cycleImage = [[UIImageView alloc] initWithFrame:self.bounds];
        [self.contentView addSubview:_cycleImage];
        _label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 20)];
        _label.backgroundColor = kRandomColor;
        
        [self.contentView addSubview:_label];
    }
    return self;
}

@end
